package com.onvifdemo.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class RemoveEmptyStringUtil {

	public static Object refreshModel(Object model, List<String> params) {
		
		removeEmpty(model, params);
		return model;
	}
	
    public static void removeEmpty(Object model, List<String> params) {  
    	Class<?> cls = model.getClass();
    	Field[] fields = cls.getDeclaredFields();
    	// 取出对象里的公共方法和属性，包括父类的
        Method[] methods = cls.getMethods();
        
    	for(Field f:fields) {
    		String fieldName = f.getName();
    		if(params.contains(fieldName)) {
    			continue;
    		}
    		String typeName = f.getType().getSimpleName();
    		if (!"String".equals(typeName)) {  
    			continue;
    		}
    		
    		try {  
            	String fieldSetName = parSetName(fieldName);
                String fieldGetname = parGetName(fieldName);
                if(null == fieldSetName || null == fieldGetname) {
                	return;
                }
                // 没有get和set不处理
                if (!checkSetMet(methods, fieldSetName) ||  !checkSetMet(methods, fieldGetname)) {  
                    return;  
                }  
                
                Method getMethod = cls.getMethod(fieldGetname); 
                Class<?> returnType = getMethod.getReturnType();
                Method fieldSetMet = cls.getMethod(fieldSetName,returnType);  
                
                Object v = getMethod.invoke(model);  
            	if(null == v) {
            		fieldSetMet.invoke(model, "");
            	}
            } catch (Exception e) {  
                e.printStackTrace();
            }   
    	}
    	  
        
    } 
    
    /** 
     * 拼接在某属性的 get方法 
     *  
     * @param fieldName 
     * @return String 
     */  
    private static String parGetName(String fieldName) {
		// TODO Auto-generated method stub
    	 if (null == fieldName || "".equals(fieldName)) {  
             return null;  
         }  
         return "get"+ fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
	}
    
    /** 
     * 拼接在某属性的 set方法 
     *  
     * @param fieldName 
     * @return String 
     */  
    public static String parSetName(String fieldName) { 
    	
        if (null == fieldName || "".equals(fieldName)) {  
            return null;  
        }  
        return "set"+ fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
        
    }
    
    /** 
     * 判断是否存在某属性的 set方法 
     *  
     * @param methods 
     * @param fieldSetMet 
     * @return boolean 
     */  
    public static boolean checkSetMet(Method[] methods, String fieldSetMet) {  
        
    	for (Method met : methods) {  
            if (fieldSetMet.equals(met.getName())) {  
                return true;  
            }  
        }  
        return false;  
        
    } 
}
